package com.bill99.util;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class JsonUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
	
	public static String convert2Json(Object object) {
		String result = null;
		
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
		CustomSerializerFactory serializerFactory= new CustomSerializerFactory();
		serializerFactory.addSpecificMapping(String.class, new StringUnicodeSerializer());
		objectMapper.setSerializerFactory(serializerFactory);
		
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			objectMapper.writeValue(byteArrayOutputStream, object);
			result = byteArrayOutputStream.toString("UTF-8");
		} catch (JsonGenerationException e) {
			LOGGER.error("object convert to json error.", e);
		} catch (JsonMappingException e) {
			LOGGER.error("object convert to json error.", e);
		} catch (IOException e) {
			LOGGER.error("object convert to json error.", e);
		}
		
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends Object> T convert2Object(String json, T t) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		T result = null;
		try {
			result = (T) mapper.readValue(json, t.getClass());
		} catch (JsonParseException e) {
			LOGGER.error("json convert to object error.", e);
		} catch (JsonMappingException e) {
			LOGGER.error("json convert to object error.", e);
		} catch (IOException e) {
			LOGGER.error("json convert to object error.", e);
		}
		
		return result;
	}

}
